package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 102 二叉树层次遍历
 */
public class LevelOrder {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode secondLeft = new TreeNode(9);
        TreeNode secondRight = new TreeNode(20);
        TreeNode thirdLeft = new TreeNode(15);
        TreeNode thirdRight = new TreeNode(7);
        // second
        secondRight.left = thirdLeft;
        secondRight.right = thirdRight;
        // root
        root.left = secondLeft;
        root.right = secondRight;

        List<List<Integer>> ret = levelOrder(root);
        System.out.println(ret);

    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> tmp = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode remove = queue.poll();
                tmp.add(remove.val);
                if (remove.left != null) {
                    queue.offer(remove.left);
                }

                if (remove.right != null) {
                    queue.offer(remove.right);
                }
            }

            ret.add(tmp);
        }

        return ret;
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
